<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" class="filter-item"  @click="openCreateWindow">新增</el-button>
      <el-button type="primary" v-if="isAllowedSendNotify" class="filter-item" style="margin-left: 40px"  @click="openNotifyWindow">发送停水通知</el-button>
    </div>
    <el-table :data="list" style="width: 100%;margin-top:30px;" border >
      <el-table-column align="center" label="#" width="50">
        <template v-slot="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="应用场景">
        <template v-slot="scope">
          {{ scope.row.sms_tpl.tpl_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" >
        <template v-slot="scope">
          {{ scope.row.status | statusFilter }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="发送阈值" >
        <template v-slot="scope">
          {{ scope.row.limit_count === 0 ? '不限制' : (scope.row.limit_type + ':' + scope.row.limit_count) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="设置时间" >
        <template v-slot="scope">
          {{ scope.row.created_at | formatDate }}
        </template>
      </el-table-column>
      <el-table-column align="center"    label="操作" width="200">
        <template v-slot="{row}">
          <el-button size="mini"   type="primary" @click="openEditWindow(row)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" custom-class="window-small-width" :title="dialogVisibleName === 'new' ? '新增短信场景设置' : '修改短信场景设置'">
      <el-form ref="smsSettingForm" :model="form.setting" :rules="form.rules" label-width="80px" label-position="left">
        <el-form-item label="场景名称" prop="sms_message_template_id">
          <el-select v-model="form.setting.sms_message_template_id" placeholder="请选择">
            <el-option
              v-for="item in templates"
              :key="item.id"
              :label="item.tpl_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.setting.status" placeholder="请选择">
            <el-option
              v-for="item in [1,2]"
              :key="item"
              :label="item | statusFilter "
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送限定" prop="limit_type">
          <el-select v-model="form.setting.limit_type" placeholder="请选择">
            <el-option
              v-for="item in ['每日','每周','每月']"
              :key="item"
              :label="item | statusFilter "
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量限定" prop="limit_count">
          <el-input v-model.number="form.setting.limit_count" placeholder="默认0不限制发送数量" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="dialogVisibleName === 'new' ? handleCreate() : handleEdit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogNotifyVisible" custom-class="window-small-width" title="发送停水通知">
      <el-form ref="smsNotifyForm" :model="notifyForm.area" :rules="notifyForm.rules" label-width="80px" label-position="left">
        <el-form-item label="区域" prop="code">
          <area-selector :areas="treeAreas"  ref="building" :area-type="2" v-on:selectArea="onSelectBuilding"></area-selector>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="notifyForm.area.date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogNotifyVisible=false">取消</el-button>
        <el-button type="primary" @click="handleNotify">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {createSmsSetting, getSmsSetting, getSmsTemplates, sendSmsNotify, updateSmsSetting} from '@/api/sms'
import moment from "moment/moment";
import AreaSelector from "@/components/area/AreaSelector.vue";
import {getAreaTree} from "@/api/area";

const typeMap = {
  1: '缴费通知',
  2: '欠费通知',
}

const defaultSetting = {
  sms_message_template_id:null,
  status:1,
  limit_type:'每日',
  limit_count:null, // 0不限制
}

export default {
  name: 'SmsSetting',
  components: {AreaSelector},
  data() {
    return {
      list: [],
      templates: [],
      treeAreas: [],
      notifyParams:null,
      typeMap:typeMap,
      form:{
        setting:Object.assign({}, defaultSetting),
        rules:{
          sms_message_template_id: [
            { required: true, message: '请选择短信模板' }
          ],
          status: [
            { required: true, message: '请选择状态' }
          ]
        }
      },
      notifyForm: {
        area:{code:'',date:''},
        rules:{
          code: [
            { required: true, message: '请选择区域' }
          ],
          date: [
            { required: true, message: '请选择日期', trigger: 'blur' }
          ]
        }
      },
      dialogVisible: false,
      dialogNotifyVisible: false,
      dialogVisibleName: 'new'
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '未启用',
        2: '已启用'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return typeMap[type]
    },
    formatDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created() {
    this.getSmsMessagesSetting()
    this.getSmsTemplates()
    this.getAreaTree()
  },
  computed: {
    isAllowedSendNotify() {
      const setting = this.list.find(item => item.sms_tpl.tpl_id === 'SMS_479045285')
       return setting !== undefined && setting.status ===2
    }
  },
  methods: {
    async getAreaTree(){
      getAreaTree({type:2}).then(response => {
        this.treeAreas = response.data
      })
    },
    async getSmsMessagesSetting() {
      const res = await getSmsSetting(this.listQuery)
      this.list = res.data.list
    },
    async getSmsTemplates() {
      const res = await getSmsTemplates()
      this.templates = res.data.list
    },
    openCreateWindow(){
      this.dialogVisible = true
      this.dialogVisibleName = 'new'
      this.form.setting = Object.assign({}, defaultSetting)
      this.$nextTick(() => {
        this.$refs['smsSettingForm'].resetFields();
      })
    },
    openEditWindow(row){
      this.dialogVisible = true
      this.dialogVisibleName = 'edit'
      this.form.setting = Object.assign({}, row)
      this.$nextTick(() => {
        this.$refs['smsSettingForm'].resetFields();
      })
    },
    openNotifyWindow(){
      this.dialogNotifyVisible = true
      this.dialogVisibleName = 'new'
      this.notifyForm.area.code = ''
      this.$nextTick(() => {
        this.$refs['smsNotifyForm'].resetFields();
      })
    },
    handleNotify() {
      this.$refs.smsNotifyForm.validate((valid) => {
        if (valid) {
          sendSmsNotify(this.notifyForm.area).then(res => {
            if(res.code === 20000){
              this.dialogNotifyVisible = false
              this.$message({
                type:'success',
                message: '发送成功!'
              });
            }else{
              this.$message.error(res.message)
            }
          })
        }
      })

    },
    onSelectBuilding(data){
      if(data !== ''){
        this.notifyForm.area.code = data.value
      }
    },
    handleCreate() {
      this.$refs['smsSettingForm'].validate(async (valid) => {
        if (valid) {
          const data = Object.assign({}, this.form.setting)
          data.limit_count = parseInt(data.limit_count)
          const res = await createSmsSetting(data)
          if(res.code === 20000){
            this.dialogVisible = false
            await this.getSmsMessagesSetting()
          }else{
            this.$message.error(res.message)
          }
        }
      })
    },
    async handleEdit(){
      const data = Object.assign({}, this.form.setting)
      data.limit_count = parseInt(data.limit_count)
      await updateSmsSetting(data).then(res => {
        if(res.code === 20000){
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.getSmsMessagesSetting()
        }
      })

    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
